<?php

declare(strict_types=1);

namespace app\api\controller\Project;

use app\BaseController;
use app\common\model\User\User as UserModel;
use app\common\model\User\Address as AddressModel;
use app\common\model\Project\Project as ProjectModel;
use app\common\model\Project\Order as OrderModel;
use app\common\model\User\Record as RecordModel;
use app\common\validate\Project\Order as OrderValidate;
use app\common\validate\User\Record as RecordValidate;
use think\exception\ValidateException;
use Exception;

class Order extends BaseController
{
    // 预约订单列表
    public function index()
    {
        $userid = $this->request->param('userid');
        // 接收预约订单的状态
        $status = $this->request->param('status');
        $User = UserModel::find($userid);
        if (!$User) {
            $this->error('用户不存在');
        }
        $where = [];

        if ($User && $userid) {
            $where['userid'] = $userid;
        }

        if ($status || $status === 0) {
            $where['status'] = $status;
        }
        $OrderList = OrderModel::withJoin('project')->where($where)->select();
        if (!$OrderList) {
            $this->error('暂无预约数据');
        }
        $this->success('查询成功', null, $OrderList);
    }
    // 预约订单新增
    public function add()
    {
        $param = $this->request->param();
        try {
            // 查询用户
            $User = UserModel::find($param['userid']);
            if (!$User) {
                throw new \Exception("用户不存在");
            }
            // 查询地址
            $Address = AddressModel::find($param['addrid']);
            if (!$Address) {
                throw new \Exception("上门地址不存在");
            }
            // 查询服务
            $Project = ProjectModel::find($param['projectid']);
            if (!$Project) {
                throw new \Exception('预约服务不存在');
            }
            // 封装数据
            $data = [
                'userid' => $param['userid'],
                'addrid' => $param['addrid'],
                'projectid' => $param['projectid'],
                'content' => $param['content'],
                'status' => 0,
                'createtime' => $param['createtime']
            ];
            // 数据验证
            validate(OrderValidate::class)->check($data);
            // 执行新增语句
            $result = OrderModel::create($data);
            // 判断
            if ($result === FALSE) {
                throw new \Exception("预约失败");
            }
        } catch (ValidateException $e) {
            $this->error($e->getError());
        } catch (\Exception $error) {
            $this->error($error->getMessage());
        }
        $this->success('预约成功');
    }
    // 预约订单支付
    public function pay()
    {
        $params = $this->request->param();
        // 开启事务
        OrderModel::startTrans();
        UserModel::startTrans();
        RecordModel::startTrans();
        try {
            $User = UserModel::find($params['userid']);
            if (!$User) {
                throw new \Exception('用户不存在');
            }
            $order = OrderModel::withJoin('project')->find($params['orderid']);
            if (!$order) {
                throw new \Exception('该预约订单不存在');
            }
            if (empty($order['price'])) {
                throw new \Exception('该预约订单未报价');
            }
            // 更新用户积分
            $point = bcsub((string)$User['point'], (string)$order['price']);
            if ($point < 0) {
                throw new \Exception('积分不足，请及时充值');
            }
            // 修改预约订单状态
            $OrderStatus = OrderModel::update(['status' => 2], ['id' => $params['orderid']]);
            if ($OrderStatus === FALSE) {
                throw new \Exception('修改预约订单状态失败');
            }
            $User->point = $point;
            $UserStatus = $User->save();
            if ($UserStatus === FALSE) {
                throw new \Exception('更新用户积分失败');
            }
            // 新增一条消费记录
            $RecordData = [
                'userid' => $User['id'],
                'point' => $order['price'],
                'content' => "您预约{$order['project']['name']}项目消费了{$order['price']}积分",
                'state' => 6
            ];
            validate(RecordValidate::class)->check($RecordData);
            $RecordStatus = RecordModel::create($RecordData);
            if ($RecordStatus === FALSE) {
                throw new \Exception("支付失败");
            }
        } catch (ValidateException $e) {
            OrderModel::rollback();
            UserModel::rollback();
            RecordModel::rollback();
            $this->error($e->getError());
        } catch (Exception $error) {
            OrderModel::rollback();
            UserModel::rollback();
            RecordModel::rollback();
            $this->error($error->getMessage());
        }
        OrderModel::commit();
        UserModel::commit();
        RecordModel::commit();
        $this->success('支付成功');
    }
    // 预约订单详情
    public function info()
    {
        $orderid = $this->request->param('orderid');
        $order = OrderModel::withJoin('project')->find($orderid);
        if (!$order) {
            $this->error('该预约订单不存在');
        }
        $this->success('查询成功', null, $order);
    }
    // 撤销预约
    public function revoke(){
        $orderid = $this->request->param('orderid');
        $Order = OrderModel::withJoin('project')->find($orderid);
        if (!$Order) {
            $this->error('预约订单不存在');
        }
        $Order->oldstatus=$Order['status'];
        $Order->status=-2;
        $OrderStatus=$Order->save();
        if ($OrderStatus===false) {
            $this->error('撤销失败');
        }
        $this->success('正在撤销，请等待管理员审核');
    }
    // 取消撤销
    public function cancel(){
        $orderid = $this->request->param('orderid');
        $Order = OrderModel::withJoin('project')->find($orderid);
        if (!$Order) {
            $this->error('预约订单不存在');
        }
        $Order->status=$Order['oldstatus'];
        $OrderStatus=$Order->save();
        if ($OrderStatus===false) {
            $this->error('取消撤销失败！');
        }
        $this->success('取消撤销成功！');
    }
    // 评分
    public function rate(){
        $orderid = $this->request->param('orderid');
        $rate = $this->request->param('rate');
        $Order = OrderModel::withJoin('project')->find($orderid);
        if (!$Order) {
            $this->error('预约订单不存在');
        }
        $Order->rate=$rate;
        $OrderStatus=$Order->save();
        if ($OrderStatus===false) {
            $this->error('评分失败！');
        }
        if ($rate >= 3) {
            $this->success('您的满意，就是我们最大的动力');
        }else{
            $this->success('非常抱歉没有给您带来愉快的预约体验');
        }
    }
    // 删除订单
    public function del(){
        $orderid = $this->request->param('orderid');
        // 查询订单是否存在
        $Order = OrderModel::where(['id' => $orderid])->find();
        if (!$Order) {
            $this->error('预约订单不存在');
        }
        // 查询用户是否存在
        $User = UserModel::find($Order['userid']);
        if (!$User) {
            $this->error('用户不存在');
        }
        $result=OrderModel::destroy($orderid);
        if ($result === FALSE) {
            $this->error('删除失败！');
        } 
        $this->success('删除成功！');
    }
}
